<template>
  <span class="JiraModal">
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" append-to-body>
      <el-form>
        <el-form-item label="创建类型" :label-width="formLabelWidth">
          <el-radio-group v-model="isNewSubmit" @change="handleRadioChange">
            <el-radio :label=1>添加issue</el-radio>
            <el-radio :label=2>关联已有issue</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form ref="createIssueFrom"  status-icon :model="createIssueFrom" :rules="rulesCreateIssueFrom" v-show="isNewSubmit === 1">
        <el-form-item label="所属项目" :label-width="formLabelWidth" prop="project">
          <el-select v-model="createIssueFrom.project" clearable placeholder="请选择项目" @change="handleSelectChange(createIssueFrom.project)">
            <el-option
              v-for="item in createIssueFrom.projects"
              :key="item.project"
              :label="item.label"
              :value="item.project">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Issue Type" :label-width="formLabelWidth" prop="issueType">
          <el-select v-model="createIssueFrom.issueType" placeholder="请选择issueType" @change="handleSelectChange(createIssueFrom.issueType)">
            <el-option
              v-for="item in createIssueFrom.issueTypes"
              :key="item.issueType"
              :label="item.label"
              :value="item.issueType">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Affect Version" :label-width="formLabelWidth" prop="affectVersion">
          <el-select v-model="createIssueFrom.affectVersion" placeholder="请选择影响版本">
            <el-option
              v-for="item in createIssueFrom.affectVersions"
              :key="item.affectVersion"
              :label="item.label"
              :value="item.affectVersion">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="严重等级" :label-width="formLabelWidth" prop="issueLevel">
          <el-select v-model="createIssueFrom.issueLevel" placeholder="请选择严重等级">
            <el-option
              v-for="item in createIssueFrom.issueLevels"
              :key="item.issueLevel"
              :label="item.label"
              :value="item.issueLevel">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Assignee" :label-width="formLabelWidth" prop="assignee">
          <el-select v-model="createIssueFrom.assignee" placeholder="请选择assignee">
            <el-option
              v-for="item in createIssueFrom.assignees"
              :key="item.assignee"
              :label="item.label"
              :value="item.assignee">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Summary" :label-width="formLabelWidth" prop="summary">
          <el-input v-model="createIssueFrom.summary" autocomplete="off" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth" prop="description">
          <mark-down-text
            @change="handleChange"
            v-model="createIssueFrom.description">
          </mark-down-text>
        </el-form-item>
        <el-form-item label="附件" :label-width="formLabelWidth" prop="attachment">
          <el-upload
            class="upload-demo"
            action="#"
            accetpt=".xlsx,.xls,.xmind"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            :on-change="handleOnChange"
            :file-list="fileList"
            :auto-upload="false"
            :before-upload="beforeUpload"
            multiple>
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-form ref="relateIssueForm"  status-icon :model="relateIssueForm" :rules="rulesRelateIssueFrom" v-show="isNewSubmit === 2">
        <el-form-item label="Issue Key" :label-width="formLabelWidth" prop="issueKey">
          <el-input v-model="relateIssueForm.issueKey" autocomplete="off" placeholder="请填写issue key,如AQM-XXX" clearable></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small"  @click="handleCancel"> 取 消 </el-button>
<!--        "dialogFormVisible = false"-->
        <el-button  size="small"  type="primary" :loading="uploading"  @click="handleOK"> 确 定 </el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import request from '@/utils/axios'
import '@/components/case/caselist/index.scss'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import getQueryString from '@/utils/getCookies';
import markDownText from '@/components/MarkdownEditor/index'
const getCookies = getQueryString.getCookie;
const initData = `{"root":{"data":{"id":"bv8nxhi3c800","created":1562059643204,"text":"中心主题"},"children":[]},"template":"default","theme":"fresh-blue","version":"1.4.43","base":0}`;
export default {
  name: 'JiraModal',
  components: { TreeSelect, markDownText},
  props: {
    title: {
      type: String,
      default: ''
    },
    operate: {
      type: String,
      default: 'edit'
    },
    productId: {
      type: String,
      default: '1'
    },
    isLoginJira: {
      type: Boolean,
      default: true
    }
  },
  data() {
    let checkIssueKey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(Number(value))) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      isNewSubmit: 1,
      fileList: [],
      fd: '',
      cardTree: ['-1'],
      uploading: false,
      bizIds: '',
      caseId: 0,
      dialogFormVisible: false,
      createIssueFrom: {
        testSuiteName: '',
        dirName: null,
        requirementId: '',
        project: '',
        issueType: '',
        affectVersion: '',
        issueLevel: '',
        assignee: '',
        projects: [{
          project: '选项1',
          label: '黄金糕'
        }, {
          project: '选项2',
          label: '双皮奶'
        }, {
          project: '选项3',
          label: '蚵仔煎'
        }, {
          project: '选项4',
          label: '龙须面'
        }, {
          project: '选项5',
          label: '北京烤鸭'
        }],
        issueTypes: [{
          issueType: 'option1',
          label: 'Bug'
        }, {
          issueType: 'option2',
          label: '缺陷'
        }],
        affectVersions: [{
          affectVersion: 'V1.0.0',
          label: 'V1.0.0 label'
        }, {
          affectVersion: 'V1.0.1',
          label: 'V1.0.1 label'
        }],
        issueLevels: [{
          issueLevel: 'P1',
          label: '致命'
        }, {
          issueLevel: 'P2',
          label: '严重'
        }, {
          issueLevel: 'P3',
          label: '一般'
        },{
          issueLevel: 'P4',
          label: '提示/建议'
        }],
        assignees: [{
          assignee: 'Hefei.Xiao',
          label: '肖和飞',
        },{
          assignee: 'Haifeng.He',
          label: '何海峰',
        }],
        summary: '请填写issue标题',
        description: '请描述issue',
      },
      relateIssueForm: {
        issueKey: ''
      },
      rulesCreateIssueFrom: {
        project: [
          { required: true, message: '请选择所属项目', trigger: 'change' },
        ],
        issueType: [
          { required: true, message: '请选择 issue type', trigger: 'change' },
        ],
        issueLevel: [
          { required: true, message: '严重等级:P1（致命错误）,P2（严重错误）,P3（一般错误）,P4（建议/提示性错误）', trigger: 'change' },
        ],
        summary: [
          { required: true, message: '请输入 issue 主题', trigger: 'change' },
        ],
        description: [
          { required: true, message: '请描述 issue 发生步骤，预期结果等', trigger: 'blur' }
        ]
      },
      rulesRelateIssueFrom: {
        issueKey: [
          { required: true, message: '请输入 issue key', trigger: 'blur' },
          { validator: checkIssueKey, trigger: 'blur' }
        ]
      },
      formLabelWidth: '200px'
    };
  },
  methods: {
    showDialog: function () {
      if (this.isLoginJira) {
        this.dialogFormVisible = true;
        this.isNewSubmit = 1;
      }
    },
    handleRadioChange: function (value){
      if (value === 2) {
        this.isNewSubmit = 2
      } else {
        this.isNewSubmit = 1
      }
    },
    handleSelectChange: function (value){
      console.log('当前选中project:', value)
    },
    getJiraProject: function (){
    },
    handleChange() {
        console.log(this.createIssueFrom.description)
    },
    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file) {
      // 文件大小限制为100M
      const fileLimit = file.size / 1024 / 1024 < 100;
      if (!fileLimit) {
        this.$message.error("上传文件大小不超过100M！");
      }
      return false;
    },
    handleCancel() {
      this.fileList = []; // 清空选择的文件列表
      this.dialogFormVisible = false
    },
    handleOK() {
      // 判断是否新建缺陷
      if (this.isNewSubmit === 1) {
        this.$refs.createIssueFrom.validate((valid) => {
          if (valid) {
            this.createNewIssue(this.createIssueFrom);
            this.dialogFormVisible = false
          } else {
            console.log('create issue error!');
            return false;
          }
        });
      } else {
        this.$refs.relateIssueForm.validate((valid) => {
          if (valid) {
            alert('已关联')
            this.dialogFormVisible = false
            this.relateIssue(this.relateIssueForm);
          } else {
            console.log('关联issue error！')
            return false;
          }
        });
      }
      // this.$emit('getIssueList')
    },
    createNewIssue(values) {
      console.log('create new issue success with: ', values)
      // let requirementId = values.requirementId;
      // let params = {
      //   productLineId: Number(this.$route.params.productLineId),
      //   creator: getCookies('username'),
      //   caseType: 0,
      //   caseContent: initData,
      //   title: values.testSuiteName,
      //   channel: 1,
      //   bizId: values.dirName ? values.dirName.join(',') : '-1',
      //   id: this.operate !== 'add' ? this.caseId : '',
      //   requirementId,
      //   description: values.description,
      // };
      //
      // // 判断是否上传了用例集文件
      // let caseFile = this.operate === 'add'? (this.fd !=='' ? this.fd.get('file'): '') :''
      //
      // let url = `/case/create`;
      // if (caseFile) {
      //   if (/(?:xmind)$/i.test(caseFile.name)) {
      //     url = `/file/import`;
      //   } else if (/(?:xls|xlsx)$/i.test(caseFile.name)) {
      //     url = `/file/importExcel`;
      //   }
      //
      //   params = new FormData();
      //   params.append('file', caseFile);
      //   params.append('creator', getCookies('username'));
      //   params.append('title', values.testSuiteName);
      //   params.append('productLineId', this.$route.params.productLineId);
      //   params.append('requirementId', requirementId);
      //
      //   params.append('description', values.description);
      //   params.append('channel', '1');
      //   params.append('bizId', values.dirName ? values.dirName.join(',') : '-1');
      // }
      // request(url, {method: 'POST', body: params}).then(res => {
      //   if (res.code === 200) {
      //     this.$message({
      //       type: 'success',
      //       message: this.operate === 'add'
      //         ? '新建测试用例集成功'
      //         : '复制测试用例集成功',
      //     });
      //     this.$emit('getDirList')
      //     if (this.operate === 'add') {
      //       let urls = `/case/edit/${this.$route.params.productLineId}/${res.data}`;
      //       console.log('跳转的路由url：', urls)
      //       this.$router.push(urls);
      //     }
      //   } else {
      //     this.$message({
      //       type: 'error',
      //       message: res.msg
      //     });
      //   }
      // });
    },
    relateIssue(values) {
      console.log('values: ', values)
      // let params = {
      //   title: values.testSuiteName,
      //   id: this.caseId,
      //   requirementId: values.requirementId,
      //   caseType: 0,
      //   description: values.description,
      //   modifier: getCookies('username'),
      //   bizId: values.dirName ? values.dirName.join(',') : '-1',
      //   channel: 1,
      // };
      // let url = '/case/edit';
      // request(url, {method: 'POST', body: params}).then(res => {
      //   if (res.code === 200) {
      //     this.$message({
      //       type: 'success',
      //       message: '更新成功'
      //     });
      //   } else {
      //     this.$message({
      //       type: 'error',
      //       message: res.msg
      //     });
      //   }
      // });
    },
    handleRemove(file, fileList) {
      console.log('handle remove:', file, fileList);
    },
    handlePreview(file) {
      console.log('handle Preview:', file);
    },
    handleOnChange(file, fileList) {
      this.fileList = [file];
      let fd = new FormData();
      fd.append("file", file.raw);
      this.fd = fd;
    },
    getCardTree: function () {
      const url = '/dir/cardTree'
      request(url, {
        method: 'GET',
        params: {
          productLineId: this.$route.params.productLineId,
          channel: 1,
        },
      }).then(res => {
        this.cardTree = res.data ? res.data.children : [];
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.text,
        children: node.children,
      }
    },
    getDetailById: function () {
      const url = '/case/detail'
      request(url, {
        method: 'GET',
        params: {
          caseId: this.caseId,
        },
      }).then(res => {
        if (res.code === 200) {
          console.log(res)
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped >
.el-row {
  margin-bottom: 20px
}
</style>
